package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.cmn.client.DictFeignClient;
import com.atguigu.yygh.enums.DictEnum;
import com.atguigu.yygh.hosp.repository.HospitalRepository;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.vo.hosp.HospitalQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HospitalServiceImpl implements HospitalService {
    @Autowired
    private HospitalRepository hospitalRepository;
    @Autowired
    private DictFeignClient dictFeignClient;

    //保存医院信息
    @Override
    public void save(Map<String, Object> paramMap) {
        //1把map转化成Hospital
        //把map转化json串
        String hospJsonStr = JSONObject.toJSONString(paramMap);
        //把json串转化成对象
        Hospital hospital = JSONObject.parseObject(hospJsonStr, Hospital.class);
        //2判断医院信息是否存在
        Hospital targetHospital =
                hospitalRepository.getByHoscode(hospital.getHoscode());
        //3判断是更新数据还是新增数据
        if(targetHospital!=null){
            //更新医院信息
            hospital.setId(targetHospital.getId());//是否进行更新判断主键
            hospital.setStatus(targetHospital.getStatus());
            hospital.setCreateTime(targetHospital.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        }else {
            //新增医院信息
            //0:未上线，1：已上线
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        }

    }

    @Override
    public Hospital getByHoscode(String hoscode) {
        Hospital hospital = hospitalRepository.getByHoscode(hoscode);
        return hospital;
    }

    //带条件带分页查询医院列表
    @Override
    public Page<Hospital> selectPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        //1创建分页对象
        //1.1创建排序对象
        Sort sort = Sort.by(Sort.Direction.DESC,"createTime");
        //1.2创建分页对象
        Pageable pageable = PageRequest.of(page-1,limit,sort);
        //2创建查询条件模板
        //2.1转化查询条件对象
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo,hospital);
        //2.2创建匹配器
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        //2.3创建模板实例
        Example<Hospital> example = Example.of(hospital,matcher);

        //3带条件带分页查询
        Page<Hospital> hospitalPage = hospitalRepository.findAll(example, pageable);

        //4 跨模块（cmn）调用查询字典，翻译编码信息
        hospitalPage.getContent().stream().forEach(item->{
            this.packHospital(item);
        });

        return hospitalPage;
    }

    //更新上线状态
    @Override
    public void updateStatus(String id, Integer status) {
        if(status.intValue()==0||status.intValue()==1){
            //根据id查询
            Hospital hospital = hospitalRepository.findById(id).get();
            //更新状态
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            hospitalRepository.save(hospital);
        }

    }
    //获取医院详情
    @Override
    public Map<String, Object> getHospInfoById(String id) {
        Map<String, Object> result = new HashMap<>();
        //1根据id查询信息，翻译补全信息
        Hospital hospital = this.packHospital(
                hospitalRepository.findById(id).get()
        );
        //2封装医院数据
        result.put("hospital",hospital);
        //3封装预约规则
        result.put("bookingRule",hospital.getBookingRule());
        //不需要重复返回数据
        hospital.setBookingRule(null);
        return result;
    }

    //查询医院名称
    @Override
    public String getHospName(String hoscode) {
        Hospital hospital = this.getByHoscode(hoscode);
        if(hospital!=null){
          return hospital.getHosname();
        }
        return "";
    }

    //根据医院名称模糊查询医院列表
    @Override
    public List<Hospital> findByHosname(String hosname) {
        List<Hospital> list =
                hospitalRepository.getByHosnameLike(hosname);
        return list;
    }
    //医院预约挂号详情
    @Override
    public Map<String, Object> getHospByHoscode(String hoscode) {
        Map<String, Object> result = new HashMap<>();
        Hospital hospital =
                this.packHospital(hospitalRepository.getByHoscode(hoscode)) ;
        result.put("hospital", hospital);
        //预约规则
        result.put("bookingRule", hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }

    private Hospital packHospital(Hospital hospital){
        String provinceCode = hospital.getProvinceCode();
        String provinceString = dictFeignClient.getName(provinceCode);
        String cityString = dictFeignClient.getName(hospital.getCityCode());
        String districtString = dictFeignClient.getName(hospital.getDistrictCode());
        String hostypeString = dictFeignClient.getName(
                DictEnum.HOSTYPE.getDictCode(), hospital.getHostype());
        hospital.getParam().put("hostypeString", hostypeString);
        hospital.getParam().put("fullAddress", provinceString + cityString + districtString + hospital.getAddress());
        return hospital;
    }


}
